// const request = require('request');
// const fs = require('fs');
const axios = require('axios');
const { randomString } = require('../utils');
const dayjs = require('dayjs');
const timezone = require('dayjs/plugin/timezone');
const utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.tz.setDefault('PRC');
// const { vipList } = require('../utils/vipList');
const { Vip } = require('../db');
const { Op } = require('sequelize');
const { sendRes } = require('./utils/responseUtils');
const { MANAGER_OPENIDS } = require('../enums');
module.exports = {
  ygoController(app) {
    app.get('/api/ygo/getCardPicById', async (req, res) => {
      // console.log('🚀 ~ req', req);
      // const { id } = req.body; // post - body
      // console.log('🚀 ~ req.query', req.query);
      const { id } = req.query;
      console.log('🚀 ~ id', id);
      if (!id) {
        res.send({
          code: -1,
          msg: 'id不能为空',
        });
      }
      const url = `https://images.ygoprodeck.com/images/cards_cropped/${ id }.jpg`;
      // console.log('🚀 ~ url', url);
      // 本地图片
      // const filePath = path.resolve(__dirname, url);
      // var stream = fs.createReadStream(filePath);
      // var responseData = [];//存储文件流
      // if (stream) {//判断状态
      //   stream.on('data', function (chunk) {
      //     responseData.push(chunk);
      //   });
      //   stream.on('end', function () {
      //     var finalData = Buffer.concat(responseData);
      //     res.write(finalData);
      //     res.end();
      //   });
      // }
      // 远程图片
      axios.get(url, {
        responseType: 'arraybuffer', //这里只能是arraybuffer，不能是json等其他项，blob也不行
      }).then(response => {
        res.set(response.headers); //把整个的响应头塞入更优雅一些
        res.end(response.data.toString('binary'), 'binary'); //这句是关键，有两次的二进制转换
      });
      // const r = request({
      //   url,
      //   method: 'GET',
      // }, (error, response, body) => {
      //   console.log('🚀 ~ response', response);
      //   if (!error && response.statusCode === 200) {
      //     res.set('content-type', 'image/jpeg');
      //     res.send(response.data);
      //   }
      // });
    });
    app.get('/api/ygo/genVip', async (req, res) => {
      const { d = 7, count = 1, isMultiUser = 0 } = req.query;
      if (d < 1) {
        res.send({
          code: -1,
          msg: '天数必须大于0',
        });
      }
      if (count < 1) {
        res.send({
          code: -1,
          msg: '数量必须大于0',
        });
      }
      const newList = [];
      for (let i = 0; i < count; i++) {
        const params = {
          // id: new Date().getTime(),
          code: randomString(16),
          // expired: dayjs.tz().add(d, 'day').add(5, 'minute').format('YYYY/MM/DD HH:mm:ss'),
          isMultiUser,
        };
        if (isMultiUser !== 1) {
          params.firstExpiredDays = d;
        }
        newList.push(params);
      }
      const newItems = await Vip.bulkCreate(newList);
      res.send({
        code: 200,
        data: newItems,
        msg: 'success',
      });
    });
    app.get('/api/ygo/getVipList', async (req, res) => {
      // console.log('🚀 ~ Vip.findAll()', JSON.stringify(await Vip.findAll()));
      // console.log('🚀 ~ vipList', vipList);
      const { code, remark = '', isDelete, ...others } = req.query;
      const where = {
        code,
        // remark: {
        //   [Op.like]: `%${ remark }%`,
        // },
        isDelete,
        ...others,
      };
      if (remark) {
        where.remark = {
          [Op.like]: `%${ remark }%`,
        };
      }
      for (const whereKey in where) {
        if (where[whereKey] === undefined) {
          delete where[whereKey];
        }
      }
      res.send({
        code: 200,
        data: await Vip.findAll({
          where,
          order: [
            ['id', 'DESC'],
          ],
          limit: 10,
        }),
        msg: 'success',
      });
    });
    app.get('/api/ygo/getVip', async (req, res) => {
      const { code = '' } = req.query;
      // const item = vipList.find(_ => {
      //   return code === _.code;
      // });
      const rlt = await Vip.findAll({
        where: {
          code: code,
          // isDelete: 0,
        },
      });
      console.log('🚀 ~ rlt', rlt);
      const list = rlt?.map(_ => _.dataValues);
      let item = list?.[0];
      console.log('🚀 ~ item', item);
      let hasExpired = false;
      if (item) {
        // 还不能使用
        if (item.expiredStart && dayjs.tz(item.expiredStart).diff(dayjs.tz()) > 0) {
          item = null;
        } else {
          if (item?.expired) {
            hasExpired = dayjs.tz(item.expired).diff(dayjs.tz()) < 0;
          } else {
            // 没有expired说明是未使用的
            item.expired = dayjs.tz().add(item.firstExpiredDays, 'day').format('YYYY/MM/DD HH:mm:ss');
            hasExpired = false;
          }
        }
      }
      res.send({
        code: 200,
        data: item ? {
          ...item, hasExpired,
        } : null,
        msg: 'success',
      });
    });
    app.get('/api/ygo/checkVip', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.query?.openId;
      const { code = '' } = req.query;
      if (!openId) {
        res.send({ code: -1, msg: '缺少参数openId' });
        return;
      }
      if (!code) {
        res.send({
          code: -1,
          msg: '缺少参数code',
        });
        return;
      }
      // const item = vipList.find(_ => {
      //   return code === _.code;
      // });
      const rlt = await Vip.findAll({
        where: {
          code: code,
          // isDelete: 0,
        },
      });
      const list = rlt?.map(_ => _.dataValues);
      // console.log('🚀 ~ rlt', rlt);
      const item = list?.[0];
      if (!item) {
        console.log('🚀 ~ 找不到这个code', code);
        res.send({
          code: -10002,
          msg: '找不到这个授权码',
        });
        return;
      }
      if (item.isDelete === 1) {
        console.log('🚀 ~ 授权码已被删除', code);
        res.send({
          code: -10003,
          msg: '授权码已被删除',
        });
        return;
      }
      if (item.isMultiUser !== 1) {
        if (item.bindOpenId !== openId) {
          console.log('🚀 ~ 授权码已他人被使用', code);
          res.send({
            code: -10004,
            msg: '授权码已他人被使用',
          });
          return;
        }
      }
      const diffExpiredTime = dayjs.tz(item.expired).diff(dayjs.tz());
      if (item.expiredStart) {
        const diffTimeStartExpiredTime = dayjs.tz(item.expiredStart).diff(dayjs.tz());
        if (diffTimeStartExpiredTime > 0) {
          res.send({
            code: -10005,
            msg: '授权码暂不可用',
          });
          return;
        }
      }
      // console.log('🚀 ~ item.expired', item.expired);
      // console.log('🚀 ~ dayjs.tz()', dayjs.tz());
      // console.log('🚀 ~ 剩余时间', code, diffExpiredTime);
      if (diffExpiredTime < 0) {
        res.send({
          code: -10001,
          msg: '授权码已过期',
        });
        return;
      }
      res.send({
        code: 200,
        data: true,
        msg: 'success',
      });
    });
    /** 续费vip */
    app.get('/api/ygo/renewVip', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.query?.openId;
      if (!MANAGER_OPENIDS.includes(openId)) {
        res.send({
          code: -1,
          msg: '只有管理员可以操作',
        });
        return;
      }
      const { code = '', d = 1 } = req.query;
      if (!code) {
        res.send({
          code: -1,
          msg: '缺少参数code',
        });
        return;
      }
      try {
        const rlt = await Vip.findAll({
          where: {
            code: code,
            isDelete: 0,
          },
        });
        const list = rlt?.map(_ => _.dataValues);
        const item = list?.[0];
        const diffTime = dayjs.tz(item.expired).diff(dayjs.tz());
        let updateExpired = '';
        if (diffTime > 0) {
          updateExpired = dayjs.tz(item.expired).add(d, 'day').format('YYYY/MM/DD HH:mm:ss');
        } else {
          updateExpired = dayjs.tz().add(d, 'day').add(5, 'minute').format('YYYY/MM/DD HH:mm:ss');
        }
        await Vip.update({
          expiredStart: dayjs.tz().format('YYYY/MM/DD HH:mm:ss'),
          expired: updateExpired,
        }, {
          where: {
            code,
          },
        });
        res.send({
          code: 200,
          data: true,
          msg: `success`,
        });
      } catch (e) {
        res.send({
          code: -1,
          msg: `续费失败, ${ e.message }`,
        });
      }
    });
    /** 删除vip */
    app.get('/api/ygo/delVip', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.query?.openId;
      if (!MANAGER_OPENIDS.includes(openId)) {
        res.send({
          code: -1,
          msg: '只有管理员可以操作',
        });
        return;
      }
      const { code = '' } = req.query;
      if (!code) {
        res.send({
          code: -1,
          msg: '缺少参数code',
        });
        return;
      }
      try {
        await Vip.update({ isDelete: 1 }, {
          where: {
            code,
          },
        });
        res.send({
          code: 200,
          data: true,
          msg: `success`,
        });
      } catch (e) {
        res.send({
          code: -1,
          msg: `删除失败, ${ e.message }`,
        });
      }
    });
    /** 启用vip */
    app.get('/api/ygo/resumeVip', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.query?.openId;
      if (!MANAGER_OPENIDS.includes(openId)) {
        res.send({
          code: -1,
          msg: '只有管理员可以操作',
        });
        return;
      }
      const { code = '' } = req.query;
      if (!code) {
        res.send({
          code: -1,
          msg: '缺少参数code',
        });
        return;
      }
      try {
        await Vip.update({ isDelete: 0 }, {
          where: {
            code,
          },
        });
        res.send({
          code: 200,
          data: true,
          msg: `success`,
        });
      } catch (e) {
        res.send({
          code: -1,
          msg: `启用失败, ${ e.message }`,
        });
      }
    });
    /** 修改Vip */
    app.get('/api/ygo/updateVip', async (req, res) => {
      // const openId = req.headers['x-wx-openid'] || req.query?.openId;
      // if (!MANAGER_OPENIDS.includes(openId)) {
      //   res.send({
      //     code: -1,
      //     msg: '只有管理员可以操作',
      //   });
      //   return;
      // }
      const { code = '', ...others } = req.query;
      if (!code) {
        res.send({
          code: -1,
          msg: '缺少参数code',
        });
        return;
      }
      const rlt = await Vip.findAll({
        where: {
          code: code,
          isDelete: 0,
        },
      });
      const list = rlt?.map(_ => _.dataValues);
      const item = list?.[0];
      if (!item) {
        res.send({
          code: -1,
          msg: `修改失败, 找不到这个码`,
        });
        return;
      }
      try {
        // 非多人适用的绑定流程
        if (others?.bindOpenId && !item.bindOpenId && item.isMultiUser !== 1) {
          others.expiredStart = dayjs.tz().format('YYYY/MM/DD HH:mm:ss');
          const firstExpiredDays = item.firstExpiredDays;
          others.expired = dayjs.tz().add(firstExpiredDays, 'day').format('YYYY/MM/DD HH:mm:ss');
        }
        await Vip.update({ ...others }, {
          where: {
            code,
          },
        });
        res.send({
          code: 200,
          data: true,
          msg: `success`,
        });
      } catch (e) {
        res.send({
          code: -1,
          msg: `修改失败, ${ e.message }`,
        });
      }
    });
    /** 搜卡 */
    app.get('/api/ygo/searchCard', async (req, res) => {
      const { keywords } = req.query;
      try {
        const searchRes = await axios.get(`https://ygocdb.com/api/v0/?search=${ keywords }`);
        sendRes(res, { data: searchRes.data.result });
      } catch (e) {
        sendRes(res, { code: -1, msg: e.message });
      }
    });
  },
};
